package com.llsydn.beijingnews.menudetailpager.tabdetailpager;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.llsydn.beijingnews.R;
import com.llsydn.beijingnews.activity.NewsDetailActivity;
import com.llsydn.beijingnews.base.BaseMenuDetailPager;
import com.llsydn.beijingnews.common.Constants;
import com.llsydn.beijingnews.domain.NewsBean;
import com.llsydn.beijingnews.domain.TabDetailBean;
import com.llsydn.beijingnews.util.CacheUtils;
import com.llsydn.beijingnews.util.LogUtil;
import com.llsydn.beijingnews.view.HorizontalScollViewPager;
import com.llsydn.refreshlistview.RefreshListView;
import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

/**
 * @author lilinshen
 * @title 页签详情页面
 * @description 请填写相关描述
 * @date 2018/10/26 9:26
 */
public class TabDetailPager extends BaseMenuDetailPager {
    public static final String READ_ARRAY_ID = "read_array_id";
    @ViewInject(R.id.viewpager)
    private HorizontalScollViewPager viewpager;
    @ViewInject(R.id.tv_title)
    private TextView tv_title;
    @ViewInject(R.id.ll_point_group)
    private LinearLayout ll_point_group;
    @ViewInject(R.id.listview)
    private RefreshListView listview;
    // 之前点高亮显示的位置
    private int prePosition;
    // 页面的数据
    private final NewsBean.DataBean.ChildrenBean childrenData;
    // 页面请求的地址url
    private String url;
    // 顶部轮播图的数据
    List<TabDetailBean.DataBean.TopnewsBean> topnews;
    // 新闻列表数据集合
    List<TabDetailBean.DataBean.NewsBean> news;
    // x.image默认图片
    public ImageOptions imageOptions;
    // 加载更多的url
    private String moreUrl;
    // 是否加载更多
    private boolean isLoadMore;
    private MyListViewAdapter adapter;
    private InternalHandler handler;

    public TabDetailPager(Context context, NewsBean.DataBean.ChildrenBean childrenData) {
        super(context);
        this.childrenData = childrenData;

        imageOptions = new ImageOptions.Builder()
                .setSize(DensityUtil.dip2px(100), DensityUtil.dip2px(100))
                .setRadius(DensityUtil.dip2px(5))
                .setCrop(true)
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setLoadingDrawableId(R.drawable.news_pic_default)
                .setFailureDrawableId(R.drawable.news_pic_default)
                .build();
    }


    @Override
    public View initView() {
        View view = View.inflate(context, R.layout.tab_detail_pager, null);
        x.view().inject(this, view);

        View topNewsView = View.inflate(context, R.layout.topnews, null);
        x.view().inject(this, topNewsView);

        // 把顶部轮播图部分视图，以头的方式添加到listview中
        // listview.addHeaderView(topNewsView);

        listview.addTopNewsView(topNewsView);

        // 设置下拉刷新
        listview.setOnRefreshListener(new MyOnRefreshListener());

        // 设置listview的item的点击监听
        listview.setOnItemClickListener(new MyOnItemClickListener());

        return view;
    }

    @Override
    public void initData() {
        super.initData();
        url = Constants.BASE_URL + childrenData.getUrl();
        LogUtil.e(childrenData.getTitle() + "联网地址：" + url);
        String saveJson = CacheUtils.getString(context, url);
        if (!TextUtils.isEmpty(saveJson)) {
            processData(saveJson);
        }
        // 联网请求数据
        getDataFromWebServer();

    }

    /**
     * listview的item点击监听事件
     */
    class MyOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int realPosition = position - 1;
            TabDetailBean.DataBean.NewsBean bean = news.get(realPosition);
            int beanId = bean.getId();
            // 取出保存的id集合
            String idString = CacheUtils.getString(context, READ_ARRAY_ID);
            // 判断是否存在,不存在才保存到缓存,并刷新适配器
            if ("".equals(idString)) {
                CacheUtils.putString(context, READ_ARRAY_ID, String.valueOf(beanId));
                adapter.notifyDataSetChanged();
            } else if (!("," + idString + ",").contains("," + beanId + ",")) {
                CacheUtils.putString(context, READ_ARRAY_ID, idString + "," + beanId);
                adapter.notifyDataSetChanged();
            }
            // 跳转到新闻浏览页面
            Intent intent = new Intent(context, NewsDetailActivity.class);
            intent.putExtra("url", Constants.BASE_URL + bean.getUrl());
            context.startActivity(intent);
        }
    }

    /**
     * 滚动监听
     */
    class MyOnRefreshListener implements RefreshListView.OnRefreshListener {

        /**
         * 下来刷新的监听
         */
        @Override
        public void onPullDownRefresh() {
            // 重新请求数据
            getDataFromWebServer();
        }

        /**
         * 加载更多
         */
        @Override
        public void onLoadMore() {
            // 加载新的数据
            if (TextUtils.isEmpty(moreUrl)) {
                Toast.makeText(context, "没有更多数据", Toast.LENGTH_SHORT).show();
                listview.onRefreshFinish(false);
            } else {
                getMoreDataFromWebServer();
            }
        }
    }

    /**
     * 加载更多数据
     */
    private void getMoreDataFromWebServer() {
        RequestParams params = new RequestParams(moreUrl);
        params.setConnectTimeout(10000);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.e("加载更多请求成功==" + result);
                // 解析数据
                isLoadMore = true;
                processData(result);
                // 隐藏加载更多控件
                listview.onRefreshFinish(false);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // LogUtil.e("页面数据请求失败==" + ex.getMessage());
                LogUtil.e("加载更多请求失败");
                // 隐藏加载更多控件
                listview.onRefreshFinish(false);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtil.e("加载更多请求取消==" + cex.getMessage());
            }

            @Override
            public void onFinished() {
                LogUtil.e("加载更多请求结束");
            }
        });

    }


    /**
     * 解析json数据
     *
     * @param json
     */
    private void processData(String json) {
        TabDetailBean bean = new Gson().fromJson(json, TabDetailBean.class);
        moreUrl = "";
        if (!TextUtils.isEmpty(bean.getData().getMore())) {
            moreUrl = Constants.BASE_URL + bean.getData().getMore();
        } else {
            moreUrl = "";
        }
        LogUtil.e("加载更多的地址：" + moreUrl);

        // 默认和加载更多
        if (!isLoadMore) {
            // 默认
            // 顶部轮播图的数据
            topnews = bean.getData().getTopnews();

            // 设置viewpager的adapter
            viewpager.setAdapter(new MyTabDetailPagerAdapter());

            // 添加红点
            addPoint();

            // 监听页面的变化设置红点和标题
            viewpager.addOnPageChangeListener(new MyOnPageChangeListener());
            tv_title.setText(topnews.get(prePosition).getTitle());

            // 准备listview的集合数据
            news = bean.getData().getNews();

            // 设置listview的adapter
            adapter = new MyListViewAdapter();
            listview.setAdapter(adapter);
        } else {
            // 加载更多
            isLoadMore = false;
            List<TabDetailBean.DataBean.NewsBean> morenews = bean.getData().getNews();

            // 添加到原来集合中，并刷新适配器
            news.addAll(morenews);
            adapter.notifyDataSetChanged();
        }

        // 发消息每隔4秒切换一次viewpager页面
        if (handler == null) {
            handler = new InternalHandler();
        }
        // 移除消息队列所有的消息和回调
        handler.removeCallbacksAndMessages(null);
        handler.postDelayed(new MyRunnable(), 4000);

    }

    /**
     * 内部的handler
     */
    class InternalHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 切换viewpager的下一个页面
            int item = (viewpager.getCurrentItem() + 1) % topnews.size();
            viewpager.setCurrentItem(item);
            handler.postDelayed(new MyRunnable(), 4000);
        }
    }

    class MyRunnable implements Runnable {
        // new在主线程,所以在主线程
        @Override
        public void run() {
            handler.sendEmptyMessage(0);
        }
    }

    /**
     * listview的apapter
     */
    class MyListViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return news.size();
        }

        @Override
        public Object getItem(int position) {
            return news.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (null == convertView) {
                convertView = View.inflate(context, R.layout.item_tabdetail_pager, null);
                viewHolder = new ViewHolder();
                viewHolder.iv_icon = convertView.findViewById(R.id.iv_icon);
                viewHolder.tv_title = convertView.findViewById(R.id.tv_title);
                viewHolder.tv_time = convertView.findViewById(R.id.tv_time);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            // 设置值给子view
            TabDetailBean.DataBean.NewsBean newsBean = news.get(position);
            String imageUrl = Constants.BASE_URL + newsBean.getListimage();
            // 联网请求图片，并设置默认图片
            x.image().bind(viewHolder.iv_icon, imageUrl, imageOptions);
            viewHolder.tv_title.setText(newsBean.getTitle());
            viewHolder.tv_time.setText(newsBean.getPubdate());

            // 设置item的颜色,(查看过变为灰色,未查看就为黑色)
            String idString = CacheUtils.getString(context, READ_ARRAY_ID);
            if ("".equals(idString)) {
                viewHolder.tv_title.setTextColor(Color.BLACK);
            } else if (!("," + idString + ",").contains("," + newsBean.getId() + ",")) {
                viewHolder.tv_title.setTextColor(Color.BLACK);
            } else {
                viewHolder.tv_title.setTextColor(Color.GRAY);
            }
            return convertView;
        }
    }

    static class ViewHolder {
        ImageView iv_icon;
        TextView tv_title;
        TextView tv_time;
    }

    /**
     * 监听viewpager，监听页面的变化设置红点和标题
     */
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int i) {
            // 设置文本
            tv_title.setText(topnews.get(i).getTitle());
            // 红点高亮
            ll_point_group.getChildAt(prePosition).setEnabled(false);
            ll_point_group.getChildAt(i).setEnabled(true);
            prePosition = i;
        }

        private boolean isDragging = false;

        // 处理自动滑动，触摸的情况（一）
        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_DRAGGING) {
                // 拖拽
                isDragging = true;
                handler.removeCallbacksAndMessages(null);
            } else if (state == ViewPager.SCROLL_STATE_SETTLING) {
                // 惯性
                isDragging = false;
                handler.removeCallbacksAndMessages(null);
                handler.postDelayed(new MyRunnable(), 4000);
            } else if (state == ViewPager.SCROLL_STATE_IDLE) {
                // 静止
                isDragging = false;
                handler.removeCallbacksAndMessages(null);
                handler.postDelayed(new MyRunnable(), 4000);
            }
        }
    }

    /**
     * 图片的adapter
     */
    class MyTabDetailPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return topnews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(context);
            imageView.setBackgroundResource(R.drawable.home_scroll_default);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY); //图片拉伸
            container.addView(imageView);
            // 联网请求图片
            String imageUrl = Constants.BASE_URL + topnews.get(position).getTopimage();
            LogUtil.e("联网请求的图片url=" + imageUrl);
            // x.image().bind(imageView, imageUrl);
            // 改用glide方式请求图片
            Glide.with(context)
                    .load(imageUrl)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imageView);

            // 处理自动滑动，触摸的情况（一）
            imageView.setOnTouchListener((view, event) -> {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 移除消息队列所有的消息和回调
                        handler.removeCallbacksAndMessages(null);
                        break;
                    case MotionEvent.ACTION_UP:
                        // 移除消息队列所有的消息和回调
                        handler.removeCallbacksAndMessages(null);
                        handler.postDelayed(new MyRunnable(), 4000);
                        break;
                }
                return true;
            });

            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    /**
     * 添加红点
     */
    private void addPoint() {
        ll_point_group.removeAllViews();
        for (int i = 0; i < topnews.size(); i++) {
            ImageView imageView = new ImageView(context);
            imageView.setBackgroundResource(R.drawable.point_selector);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px(5), DensityUtil.dip2px(5));
            if (i == 0) {
                imageView.setEnabled(true);
            } else {
                imageView.setEnabled(false);
                params.leftMargin = DensityUtil.dip2px(8);
            }
            imageView.setLayoutParams(params);
            ll_point_group.addView(imageView);
        }
    }

    /**
     * 联网请求数据
     */
    private void getDataFromWebServer() {
        RequestParams params = new RequestParams(url);
        params.setConnectTimeout(10000);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.e("页面数据请求成功==" + result);
                // 缓存数据
                CacheUtils.putString(context, url, result);
                // 解析数据
                processData(result);
                // 隐藏下拉刷新控件-更新时间，并重新显示数据
                listview.onRefreshFinish(true);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // LogUtil.e("页面数据请求失败==" + ex.getMessage());
                LogUtil.e("页面数据请求失败");
                // 隐藏下拉刷新控件-不更新时间
                listview.onRefreshFinish(false);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtil.e("页面数据请求取消==" + cex.getMessage());
            }

            @Override
            public void onFinished() {
                LogUtil.e("页面数据请求结束");
            }
        });
    }
}
